package com.cskaoyan.market.controller.admin;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.service.admin.MarketAuthService;
import com.cskaoyan.market.shiro.CskaoyanToken;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.admin.ResponseVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AdminAuthController
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/5/5 10:18
 * @Version V1.0
 **/
@RestController
@RequestMapping("admin/auth")
public class AdminAuthController {

    @Autowired
    SecurityManager securityManager;
    @Autowired
    MarketAuthService adminService;

    /**
     * @MethodName logout
     * @Description  登出操作
     * @param: req  用于获得session
     * @return: com.cskaoyan.market.vo.ResultVo
     * @Author MZ
     * @Date 10:31 2023/5/17
     **/
    @PostMapping("logout")
    public Object logout(HttpServletRequest req){
        HttpSession session = req.getSession();
        // 清空session
        session.invalidate();
        return new ResponseVo(0,"成功");
    }

    /**
     * 登录的业务逻辑：
     * 1.获取请求参数，但是记住不可以使用request.getparameter来获取
     * 2.处理具体的业务逻辑
     * 3.返回响应体---和公网一致即可
     */
    @PostMapping("login")
    public Object login(@RequestBody Map<String,String> map) {

        String username = map.get("username");
        String password = map.get("password");
        //获取完请求参数之后，怎么办？
//        //首先做一些校验----放在controller中去做更为合适一些
//        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
//            return new ResponseVo(401,"参数不对");
//        }
//        //根据size是否是1还是0判断用户是否登录成功
//        List<MarketAdmin> marketAdmins = adminService.login(username, password);
//        //根据code的值，返回不同的响应结果
//        if(marketAdmins.size() == 0){
//            //用户名、密码错误
//            return new ResponseVo(605, "用户名、密码错误");
//        }

        // 进行认证操作
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        // 传入参数
        CskaoyanToken token = new CskaoyanToken(username,password,"admin");
        try {
            subject.login(token);
            System.out.println("登陆成功！");
        } catch (Exception e) {
            System.out.println("登陆失败，用户名密码错误");
            // {"errno":700,"errmsg":"账号不存在"}
            return ResponseUtil.loginFail();
        }
        // 登陆成功
        MarketAdmin admin = adminService.getAdminByUsername(username,password);

        ResponseVo responseVo = new ResponseVo();

        Map<String, Object> result = new HashMap<>();
        Map<String, String> adminInfoMap = new HashMap<>();
        adminInfoMap.put("nickName", username);
        adminInfoMap.put("avatar", admin.getAvatar());

        result.put("adminInfo", adminInfoMap);
        //登录成功之后的凭证可以使用session的编号来充当
        Session session = subject.getSession();

        session.setAttribute("admin", admin);

        result.put("token", session.getId());

        responseVo.setErrno(0);
        responseVo.setErrmsg("成功");
        responseVo.setData(result);
        return responseVo;
    }

    /**
     * 管理员个人中心接口
     * 三步走：
     * 1.获取接收请求参数-无
     * 2.处理具体的业务逻辑---只需要提供3所需要的数据即可
     * 3.返回响应
     * @param
     */
    @RequiresAuthentication
    @GetMapping("info")
    public Object info() {
        ResponseVo responseVo = new ResponseVo();

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");

        Integer[] roleIds = admin.getRoleIds();
        //关于roles以及perms是属于权限管理部分的内容，shiro，直接固定写即可
        Map<String, Object> result = adminService.info(admin,roleIds);

        responseVo.setErrno(0);
        responseVo.setErrmsg("成功");
        responseVo.setData(result);
        return responseVo;

    }
}
